package com.mxpio.erp.common.jpa.policy;

import com.mxpio.erp.common.jpa.entity.ResType;
import com.mxpioframework.common.util.BeanReflectionUtils;
import com.mxpioframework.common.util.SpringUtil;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.policy.impl.AbstractGeneratorPolicy;
import com.mxpioframework.jpa.policy.impl.CrudType;
import com.mxpioframework.system.service.SnRuleService;

public class ResCodeGeneratorPolicy extends AbstractGeneratorPolicy {

	@Override
	public CrudType getType() {
		return CrudType.SAVE;
	}

	@Override
	protected Object getValue(Object entity, String field) {
		Object value = BeanReflectionUtils.getPropertyValue(entity, field);
		if(value == null || "".equals(value)){
			String clazzName = BeanReflectionUtils.getClass(entity).getSimpleName();
			try {
				ResType type = JpaUtil.linq(ResType.class).equal("typeClass", clazzName).findOne();
				StringBuffer expression = new StringBuffer(type.getTypePrefix());
				for(int i=0 ;i < type.getTypeSize(); i++){
					expression.append("#");
				}
				SnRuleService snRuleService = SpringUtil.getBean(SnRuleService.class);
				value = snRuleService.execute(expression.toString(), null);
			}catch (Exception e) {
				value = null;
			}
		}
		
		return value;
	}

}
